package cc.shacocloud.luanniao.web.controller

import cc.shacocloud.luanniao.core.model.dto.input.NamespaceInput
import cc.shacocloud.luanniao.core.service.NamespaceService
import cc.shacocloud.luanniao.web.controller.interceptor.AuthInterceptor.Companion.currentUser
import cc.shacocloud.luanniao.web.model.convert.toOutput
import cc.shacocloud.luanniao.web.model.dto.output.NamespaceOutput
import org.springframework.dao.DuplicateKeyException
import org.springframework.validation.BeanPropertyBindingResult
import org.springframework.validation.BindException
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ServerWebExchange

/**
 * 命名空间控制器
 * @author 思追(shaco)
 */
@Validated
@RestController
@RequestMapping("/api/namespace")
class NamespaceServiceController(
    val namespaceService: NamespaceService,
) {

    /**
     * 创建命名空间
     */
    @PostMapping
    suspend fun create(
        @Validated @RequestBody input: NamespaceInput,
        exchange: ServerWebExchange,
    ): NamespaceOutput {
        val currentUserPo = exchange.currentUser()

        try {
            return namespaceService.create(input, currentUserPo).toOutput()
        } catch (e: DuplicateKeyException) {
            val bindingResult = BeanPropertyBindingResult(input, "input")
            bindingResult.rejectValue("name", "名称已经存在")
            throw BindException(bindingResult)
        }

    }

}